import { defineStore } from 'pinia';
import sheep from '@/sheep';

const family = defineStore({
  id: 'family',
  state: () => ({
    // 家庭列表
    list: [],
    genealogyList: [],
    treeInfo: {},
    // 消息通知
    unread_family: [],
    unread_genealogy: [],
    unread_user: [],
    // 消息提醒
    unread_message: [],
    // 树状态是否更改
    isSetStatus: false,
    // 树谱当前显示了多少人
    memberNum: 0,
    // 树谱下的每个组件的集合
    treeList: new Map(),
    // 树谱中心点上的信息
    centerInfo: {},
    // 树谱完善资料传递的参数
    perfectOptions: {},
    // 树谱添加人的信息
    perfectInfo: {},
    // 树谱中添加成员是否显示折叠以及添加人的信息
    memberInformation:{}
  }),
  actions: {
    // 获取家庭列表
    async getList() {
      const { data } = await sheep.$api.family.getUserFamily();
      data.familys.forEach(item => {
        let arr = [];
        item.member_limit.forEach((i, index) => {
          if (index < 6) {
            arr.push(i);
          }
        });
        item.member_limit = arr;
      });
      this.list = data.familys;
    },
    // 获取家谱列表
    async getFamilyTree() {
      const { data } = await sheep.$api.genealogy.getGenealogySelect();
      this.genealogyList = data.list;
    },
    // 退出时设置家庭列表
    async setList() {
      this.list = [];
    },
    // 退出时设置家谱列表
    async setFamilyTree() {
      this.genealogyList = [];
    },
    // 设置家谱树
    async setGenealogyTree(id, top_id = 0, is_firstScreen = false, is_all = 0, headcount = 0) {
      // const { data, code } = await sheep.$api.genealogy.getTreeLists({ genealogy_id: id });
      // this.treeInfo = data;
      if (!is_firstScreen) {
        const { data, code } = await sheep.$api.genealogy.getGenealogyTreeListV4({
          genealogy_id: id,
          tree_limit: 500,
          top_id,
        });
        this.treeInfo = data;
      } else {
        if (is_all == 0) {
          const { data, code } = await sheep.$api.genealogy.getGenealogyTreeListByCenterId({
            genealogy_id: id,
            tree_limit: 500,
            top_id,
          });
          this.treeInfo = data;
        } else {
          const { data, code } = await sheep.$api.genealogy.getGenealogyTreeListV4({
            genealogy_id: id,
            tree_limit: headcount,
            top_id,
          });
          this.treeInfo = data;
        }
      }
    },
    // 退出时设置家谱树
    async hideGenealogyTree() {
      this.treeInfo = {};
    },
    // 设置显示人数
    async setMemberNum(num) {
      this.memberNum = num;
    },
    // 设置树谱集合
    async setTreeList(data) {
      // 建立一个map集合
      // 验证 data 是否存在
      if (data && data.memberInfo && data.memberInfo.id) {
        this.treeList.set(data.memberInfo.id, data.memberInfo);
      } else {
        console.error('Invalid data. Cannot add member info.');
      }
    },
    // 中心点信息
    setCenterInfo(data) {
      this.centerInfo = data;
    },
    // 添加家谱树成员
    async addGenealogyTree(data) {
      this.perfectInfo = data;
    },
    // 家谱树状态更改
    async setGenealogyTreeStatus(flag) {
      this.isSetStatus = flag;
    },
    // 获取未读消息通知
    async getFamilyRemindList() {
      // const { data } = await sheep.$api.notice.getUnreadMessage();
      // console.log('获取到的消息通知=>', data);
      // if(!!data.family && data.family.length > 0){
      //   data.family.forEach(item =>{
      //     this.unread_message.push(item)
      //   })
      // }
      // if(!!data.genealogy && data.genealogy.length > 0){
      //   data.genealogy.forEach(item =>{
      //     this.unread_message.push(item)
      //   })
      // }
      // if (!!data.user) {
      //   data.user.forEach(item => {
      //     if (item.type == 'friend_new') {
      //       this.unread_user.push(item);
      //     }
      //   });
      // }
    },
    // 接收到的消息组装
    async getUnreadMessage(data) {
      this.unread_message.push(data);
    },
    // 添加好友消息组装
    async getUnreadUser(data) {
      this.unread_user.push(data);
    },
    // 清空未读消息
    async clearUnread() {
      this.unread_message = [];
    },

    // #ifdef H5
    // 初始化本地数据库
    async initData(name = 'genealogy') {
      return new Promise((resolve, reject) => {
        let db = null;
        const request = window.indexedDB.open(name, 1);
        request.onerror = () => {
          console.log('数据库打开失败');
          reject();
        };
        request.onsuccess = (event) => {
          db = event.target.result;
          resolve(db);
        };
        request.onupgradeneeded = (event) => {
          db = event.target.result;
          console.log(db.objectStoreNames.contains(name));
          if (!db.objectStoreNames.contains(name)) {
            const treeSpectrumCache = db.createObjectStore(name, { keyPath: 'id', autoIncrement: true });
            treeSpectrumCache.createIndex('info', 'info', { unique: true });
          }
          resolve(db);
        };
      });
    },

    // 设置数据
    async setData(db, data) {
      return new Promise((resolve, reject) => {
        db.transaction(['sq_sql'], 'readwrite').objectStore('sq_sql').add(data);
        resolve(true);
      });
    },
    // #endif

    async setPerfectOptions(data) {
      this.perfectOptions = data;
    },

    // 设置添加人的信息
    async setMemberInformation(data) {
      this.memberInformation = data;
    },
  },
});

export default family;